<template>
  <div>
    <query-table  ref="batch_table" :page-size="20"
                  :table-max-height="tableMaxHeight"
                  :columns="columns"
                  :append-buttons="appendQueryButtons" :query-fields="queryFields"
                  :detail-fields="infoFields" base-url="/batch_info"
                  v-loading="isLoading" selectable show-index/>

    <el-dialog
        width="80%"
        title="导入数据"
        :visible="showFeaImport"
        :close-on-click-modal="false"
        @close="showFeaImport=false"
    >
      <el-main>
        <upload-excel v-if="!preEvaluationExcelData" :on-success="handleFileParseSuccess" :before-upload="beforeUpload"/>
        <excel-view v-if="preEvaluationExcelData" :data="preEvaluationExcelData"  max-height="500"></excel-view>
        <el-divider/>
        <el-button style="float: right" type="primary" :loading="isLoading" @click="importExcel">确认并导入</el-button>
        <el-button v-if="preEvaluationExcelData" style="float: right;margin-right:10px;" :loading="isLoading" @click="preEvaluationExcelData=null;">重新选择</el-button>
      </el-main>
    </el-dialog>
    </div>

</template>

<script>
import RecordTable from "../../components/record-table";
const moment = require('moment');
import excel from "../../util/excel";
import Upload from "../../components/upload";
export default {
  name: "BatchList",
  components: {RecordTable},
  $$route:{
    meta:{
      title:'任务管理'
    }
  },
  props:{
    //页面总体高度
    pageHeight:{
      type:Number,
      defaultValue: 500
    }
  },
  data() {
    return {
      showFeaImport:false,
      isLoading: false,
      currentRow:'',
      preEvaluationExcelData:null,
      productTypeMap:[],
      batchTypeMap:[],
      queryFields: [
        {
          id: 'name',
          name: '名称',
          colSpan: 5
        },
        {id: 'year', name: '任务年度',component: 'year-picker', colSpan: 4},
        {id: 'productType', name: '产品类型',colSpan: 4,component: {id: 'meta-select', type: 'product-type'}},
        // {id: 'quality', name: '任务性质',colSpan: 4,component: {id: 'meta-select', type: 'batch-quality',load:this.loadBatchQuality}},
        {id: 'type', name: '任务类型' ,colSpan: 4,component: {id: 'meta-select', type: 'batch-type'}},
      ],
      columns: [
        {id: 'name', name: '名称',},
        {id: 'totalInvest', name: '建设投资', width: 120,unit:'万元'},
        {id: 'projectTotalCount', name: '项目数（个）', width: 50},
        {id: 'projectPassCount', name: '合格项目数（个）', width: 50},
        {id: 'year', name: '任务年度', width: 50},
        {id: 'productType', name: '产品类型',width:60,type:'meta',source:'product-type'},
        {id: 'quality', name: '任务性质',width:60,type:'meta',source:'batch-quality'},
        {id: 'type', name: '任务类型' ,width:100,type:'meta',source:'batch-type'},
        {
          id: 'state', name: '状态', component: {
            id: 'tag', getType: (val) => {
              if (val == 'complete') {
                return 'success';
              }
            }
          }, width: 90, type:'meta',source:'batch-state'
        },
        {id: 'createUser', name: '创建人', type: 'user', width: 100, showOverflowTooltip: true},
        {
          id: 'createTime', name: '创建时间', width: 80,formatter: (value) => {
            if (value === null) {
              return ''
            }
            let dt = new Date(value)
            return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
          }
        },
        {
          id: 'operation', name: '操作', type: 'button', width:290, children: [
            {text: '详情', type:'primary', click:(row)=>{ this.openPage('/batch/manage',row.id)}},
            {text: '编辑', operation: 'edit',isHide:(row)=>{return !this.checkPermission("batch:update") || row.state === "complete"}},
            {text: '锁定', type:'success', click:(row)=>{this.lockManage(row,true);},isHide:(row)=>{return !this.checkPermission("batch:update") || row.state === "complete"}},
            {text: '解锁', type:'danger', click:(row)=>{this.lockManage(row,false);},isHide:(row)=>{return !this.checkPermission("batch:update") || row.state === "init"}},
            {text: '删除', type:'danger', operation: 'delete',isHide: (row) => {return (row.state === "complete" ||  !this.checkPermission('batch:delete'));}},
          ]
        },
      ],

      appendQueryButtons: [
        {text: '新增', type: 'success', operation: 'create',isHide:()=>{return !this.checkPermission("batch:create")}},
      ],
      infoFields: [
        {
          id: 'name',
          name: '名称',
          rules: [{required: true, message: "请输入名称", trigger: "blur"}],
          colSpan: 24,
        },
        {
          id: 'year',
          name: '任务年度',
          defaultValue:new Date().getFullYear(),
          colSpan: 12,
          component:{id:'year-picker',change:this.handleChange,}
        },
        {
          id: 'productType',
          name: '产品类型',
          colSpan: 12,
          component:{id:'meta-select',type:'product-type',change:(val,row)=>{
              if(val =='oil') {
                row.modelId = '105f798a831d4d919662c96a3d13c59f'
              } else if(val =='gas') {
                row.modelId = 'e077d3a2e95a4e25afccc8e445bed938'
              }
            this.handleChange(row.productType,row)
            },},
          isDisabled:(row)=>{
            return row.id
          }
        },
        {
          id: 'quality',
          name: '任务性质',
          colSpan: 12,
          defaultValue:'out_put',
          component: {id: 'meta-select', type: 'batch-quality',
           // defaultSelect:'first',
            load:this.loadBatchQuality,
            change: (type,row)=>{
              if (type=='reserves') {
                row.modelId='36f18f5a1d314de2940c38524211fa90'
              } else {
                row.modelId="105f798a831d4d919662c96a3d13c59f"
              }

            }
          },
          isDisabled:(row)=>{
            return row.id
          }
        },
        {
          id: 'type',
          name: '任务类型',
          colSpan: 12,
          component:{
            id:'meta-select',
            type:'batch-type',
            change:this.handleChange
          },
          isDisabled:(row)=>{
            return row.quality!= 'out_put'
          }
        },
        {
          id: 'paramVersion',
          name: '公共参数',
          component: {
            id: 'data-select',
            dataUrl: '/settings/common_param_version/queryPublish',
            defaultSelect:'first'
          },
          isDisabled: (row) => {
            return row.id
          },
          // isHide:()=>{return true},
          colSpan: 12,
          rules: [{required: true, message: "请选择公共参数", trigger: "blur"}],
        },
        {
          id: 'modelId',
          name: '评价模型',
          defaultValue:'105f798a831d4d919662c96a3d13c59f',
          component: {
            id: 'data-select',
            dataUrl: '/settings/model/publish/data',
            defaultSelect:'first',
          },
          rules: [{required: true, message: "请选择评价模型", trigger: "blur"}],
          isDisabled: (row) => {
            return row.id
          },
          colSpan: 12
        },

      ],
      paramColumns:[
        {name: '序号', id: 'index', readonly: true},
        {name: '年度', id: 'year',readonly: true},
        {name: '油价(元/吨)', id: 'price'},
        {name: '原油产量调整系数', id: 'oilAdjustRate'},
        {name: '投资调整系数', id: 'investAdjustRate'},
        {name: '成本调整系数', id: 'costAdjustRate'},
      ],
    }
  },
  computed:{
    //表格最大高度，自适应
    tableMaxHeight(){
      return this.pageHeight - 100;
    }
  },
  created() {
    this.loadMetaNameMap('product-type',map => {
      this.productTypeMap = map;
    }),

        this.loadMetaNameMap('batch-type',map => {
          this.batchTypeMap = map;
        })
  },
  methods:{
    loadBatchQuality(list) {
      let result = []
      for (let item of list) {
        if (item.id != 'plan') {
          result.push(item)
        }
      }
      return result
    },
    lockManage(row,lockState) {
      this.$confirm('确定' + (lockState ? '锁定' : '解锁') + '【'+row.name+'】评价任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.state = lockState ? "complete" : "init";
        this.$post("/batch_info/update", row, (response) => {
          if (response.code == 0) {
            this.$refs['batch_table'].reload();
          }
        })
      })
    },
    /**
     *导入文件解析
     */
    handleFileParseSuccess(workbook) {
      this.preEvaluationExcelData = excel.parseXlsxWorkbook(workbook);
    },
    beforeUpload(file) {
      this.files = file;
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (extension !== 'xlsx' && extension !== 'xls') {
        this.$message({
          message: '只能上传Excel（即后缀是.xlsx或者.xls)的文件.',
          type: 'warning'
        })
        return false;
      }
      if (isLt5M) {
        return true;
      }

      this.$message({
        message: '请不要上传大于5MB的文件.',
        type: 'warning'
      })
      return false;
    },
    importExcel(e){
      if(!e.target||!e.target.files||!e.target.files.length) {
        e.target.files = this.files;
       // return;
      }
      const loading = this.openLoading('正在处理...');
      let formData = new FormData();
      formData.append("multipartFile", e.target.files[0])
      this.$message.success('模拟保存成功！');
      loading.close();
      this.showFeaImport = false;

      // this.$post("/feasibility_data/import?projectId=" + this.projectInfo.id, formData, (response) => {
      //   this.$message.success('保存成功！');
      //     this.loadFeasibilityData(this.projectInfo.id,this.loadComputeResult);
      //     this.showFeaImport = false;
      // }, (response) => {
      //   this.$refs['excel-upload-input'].value = null
      //   loading.close();
      // })
      // this.$post("/feasibility_data/read_excel?projectId=" + this.projectInfo.id, formData, (response) => {
      //   this.$message.success('解析成功，请进行确认并保存');
      //   // this.loadFeasibilityData(this.projectInfo.id,this.loadComputeResult);
      //   let projectData = response.data;
      //   this.initProjectData(projectData);
      //   this.projectData = projectData;
      //   this.showFeaImport = false;
      // }, (response) => {
      //   this.$refs['excel-upload-input'].value = null
      //   loading.close();
      // })
    },
    uploadFile() {
      // 装载成formData数据
      this.isLoading = true;
      this.excelLoading = true;
      const formData = new FormData();
      formData.append('file', this.files, this.files.name);
      formData.append('projectId', this.projectInfo.id);
      axios.post(Vue.prototype.$ctx+'/feasibility_data/pre_eva_file/upload',formData,{
        'Content-type' : 'multipart/form-data'
      }).then(response=>{
        if(response.data.code==0) {
          this.projectDetailData.preEvaluationFileId = response.data.data;
          this.excelLoading = true;
          this.$get('/feasibility_data/pre_eva_file/preview',{fileId:this.projectDetailData.preEvaluationFileId},(response)=>{
            this.projectDetailData.preEvaluationExcelData = response.data;
            this.preEvaluationExcelData = null;
          },()=>{
            this.excelLoading = false;
          });
          // this.$message.success("上传成功")
          this.showFeaImport = false;
        } else {
          this.$message.warning(response.data.msg);
        }
        this.isLoading = false;
        // 上传成功后的处理
      },err=>{
        console.error(err);
        this.$message.error("上传文件出错")
        this.isLoading = false;
        this.excelLoading = false;
        // 出现错误时的处理
      })
    },

    handleChange(val,data){
      console.log(val,data)
      if(data && data.year && data.type && data.productType){
        let type =this.batchTypeMap[data.type];
        let productType = this.productTypeMap[data.productType];
        data.name = '大庆油田'+data.year+'年'+productType+type+'经济评价';
      }
    },
  }
}
</script>
